<template>
  <div id="Score">
    <div class="mt-4">
      <el-input
        v-model="queryValue"
        placeholder="请输入查询值"
        class="input-with-select"
        style="float: left;width: 300px"
        @keydown.enter.native="selectStu(selectValue, queryValue)"
      >
        <template #prepend>
          <el-select v-model="selectValue" placeholder="请选择查询项" style="width: 135px">
            <el-option label="姓名" value="sname" />
            <el-option label="课程名" value="cname" />
          </el-select>
        </template>
        <template #append>
          <el-button :icon="Search" @click="selectStu(selectValue, queryValue)" />
        </template>
      </el-input>
    </div>
    <el-button plain type="primary" circle style="margin-left: 20px" @click="clickAllStu" >All</el-button>
    <el-button plain :icon="Plus" :round="true" style="float: right" @click="ScoreDialogVisible=true">添加成绩</el-button>
    <el-table :data="scoreAllData" table-layout="auto" >
      <el-table-column fixed prop="sname" label="学生姓名" />
      <el-table-column prop="cname" label="课程名" />
      <el-table-column prop="score" label="课程分数" />
      <el-table-column label="操作" header-align="center" width="210">
        <template #default="scope">
          <el-button plain @click="clickToModify(scope.row)" type="primary" :icon="Edit">修改</el-button>
          <el-divider direction="vertical" />
          <el-popconfirm
            confirm-button-text="确定"
            @confirm="clickToDelete(scope.row)"
            cancel-button-text="取消"
            icon-color="#626AEF"
            title="你确定要删除吗？"
          >
            <template #reference>
              <el-button type="danger" plain :icon="Delete">删除 </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      hide-on-single-page
      :page-sizes="[10]"
      layout="prev, pager, next"
      :total="total"
      :current-page="currentPage"
      @current-change="handleCurrentChange"
    />
  </div>
  <el-dialog
    v-model="ScoreDialogVisible"
    title="添加成绩"
    width="30%"
    :before-close="resetForm"
  >
    <el-form
      ref="scoreFormRef"
      :model="scoreForm"
      :rules="scorerules"
      label-width="100px"
      style="overflow: hidden;padding-right: 50px;width: 60%;margin: 10px auto"
    >
      <el-form-item label="姓名:" prop="sid" >
        <el-cascader placeholder="请选择学生" v-model="scoreForm.sid" :options="stuSelect" clearable :show-all-levels="false" />
      </el-form-item>
      <el-form-item label="课程:" prop="cid">
        <el-select v-model="scoreForm.cid" class="m-2" placeholder="请选择课程">
          <el-option
            v-for="score in courseAllData"
            :key="score.cid"
            :label="score.cname"
            :value="score.cid"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="成绩:" prop="score" >
        <el-input placeholder="请输入成绩" v-model="scoreForm.score" clearable autocomplete="off" style="width: 215px;" />
      </el-form-item>
      <el-form-item style="float: right">
        <el-button-group>
          <el-button type="success" @click="submitForm(scoreFormRef)">确认</el-button>
          <el-button type="info" @click="resetForm">取消</el-button>
        </el-button-group>
      </el-form-item>
    </el-form>
  </el-dialog>
  <el-dialog
    v-model="ScoreModifyDialogVisible"
    title="修改成绩"
    width="30%"
    :before-close="resetModifyForm"
  >
    <el-form
      ref="scoreModifyFormRef"
      :model="scoreModifyForm"
      :rules="scoreModifyrules"
      label-width="100px"
      style="overflow: hidden;padding-right: 50px;width: 60%;margin: 10px auto;"
    >

      <el-form-item label="姓名:" prop="sname" >
        <el-input v-model="scoreModifyForm.sname" disabled autocomplete="off" style="width: 215px;" />
      </el-form-item>
      <el-form-item label="课程:" prop="cname">
        <el-input v-model="scoreModifyForm.cname" disabled autocomplete="off" style="width: 215px;" />
      </el-form-item>
      <el-form-item label="成绩:" prop="score" >
        <el-input-number v-model="scoreModifyForm.score" :min="1" :max="100" />
      </el-form-item>
      <el-form-item style="float: right">
        <el-button-group>
          <el-button type="success" @click="submitModifyForm(scoreModifyFormRef)">确认</el-button>
          <el-button type="info" @click="resetModifyForm">取消</el-button>
        </el-button-group>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import axios from "axios";
import {ref, reactive, unref} from "vue";
import {Search,Delete} from "@element-plus/icons-vue";
import {Edit,Plus} from "@element-plus/icons-vue"
import {ElMessageBox, ElNotification} from "element-plus";

export default {
  name: "ScoreSys",
  setup() {

    let scoreFormRef = ref()
    let scoreAllData = ref([])
    let total = ref(0)
    let queryValue = ref()
    let selectValue = ref()
    let ScoreDialogVisible = ref(false)
    let courseAllData = ref()
    let scoreModifyForm = ref({
      sid: '',
      cid: '',
      score: 0
    })
    let currentPage = ref(1)
    let scoreModifyFormRef = ref()
    let selectMode = ref(1)  // 1：全部，2：条件查询
    const scoreModifyrules = {
      score: [
        { required: true, trigger: 'blur', validator: checkScore }
      ]
    }
    let ScoreModifyDialogVisible = ref(false)

    /* 弹出层 */
    let myscoreForm = ref(null)
    let scoreForm = ref({
      sid: '',
      cid: '',
      score: ''
    })
    let stuSelect = ref([])
    const scorerules = {
      sid: [
        { required: true, trigger: 'blur', validator: checkSid },
      ],
      cid: [
        { required: true, trigger: 'blur', validator: checkCid }
      ],
      score: [
        { required: true, trigger: 'blur', validator: checkScore }
      ]
    }
    function checkSid (rule, value, callback) {
      if (!value) {
        return callback(new Error('请选择学生'));
      } else {
        callback()
      }
    }
    function checkCid (rule, value, callback) {
      if (!value) {
        return callback(new Error('请选择学生'));
      } else {
        callback()
      }
    }
    function checkScore (rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入成绩'));
      } else if (value < 0 || value > 100) {
        return callback(new Error('成绩的范围应该在 0-100 之间'));
      }else {
        callback()
      }
    }
    
    getStuSelect("/api/getStuAll")
    getScoreAll("/api/getScoreData?pageNum=1&pageSize=10")
    getCourseAll("/api/getCourseAll")

    function getScoreAll(url) {
      axios.get(url, {
        headers: {
          token: localStorage.getItem("token")
        }
      }).then((res) => {
        scoreAllData.value = res.data.data.scoreList
        total.value = res.data.data.total
      })
    }
    function selectStu(s, c) {
      if (s == null || c == null) {
        clickAllStu()
      }
      selectMode.value = 2
      currentPage.value = 1
      getScoreAll("/api/getScoreBy?pageNum=1&pageSize=10&selectValue="+s+"&queryValue="+c)
    }
    function getStuSelect(url)  {
      axios.get(url, {
        headers: {
          token: localStorage.getItem("token")
        }
      }).then((res) => {
        stuSelect.value = res.data.data
      })
    }
    function getCourseAll(url) {
      axios.get(url, {
        headers: {
          token: localStorage.getItem("token")
        }
      }).then((res) => {
        courseAllData.value = res.data.data
      })
    }
    const clickToModify = (row) => {
      ScoreModifyDialogVisible.value = true
      scoreModifyForm.value = JSON.parse(JSON.stringify(row))
    }
    const handleCurrentChange = (val) => {
      currentPage.value = val
      if (selectMode.value === 1) {
        getScoreAll("/api/getScoreData?pageNum="+val+"&pageSize=10")
      } else if (selectMode.value === 2) {
        getScoreAll("/api/getScoreBy?pageNum="+val+"&pageSize=10&selectValue="+selectValue.value+"&queryValue="+queryValue.value)
      }
    }
    const submitForm = (formEl) => {
      if (!formEl) return
      formEl.validate((valid) => {
        if (valid) {
          axios.post("/api/scoreAdd", scoreForm.value, {
            headers: {
              token: localStorage.getItem("token")
            }
          }).then(res => {
            if (res.data.code === 200) {
              ElNotification({
                title: '成功',
                message: res.data.msg,
                type: 'success',
                offset: 100,
              })
            } else {
              ElNotification({
                title: '错误',
                message: res.data.msg,
                type: 'error',
                offset: 100,
              })
            }
            selectMode.value = 1
            currentPage.value = 1
            getScoreAll("/api/getScoreData?pageNum=1&pageSize=10")
          })
          ScoreDialogVisible.value = false
          unref(scoreFormRef).resetFields()
        }
      })
    }
    const resetForm = () => {
      ScoreDialogVisible.value = false
      unref(scoreFormRef).resetFields()
    }
    const clickToDelete = (row) => {
      axios.post("/api/deleteScore", row, {
        headers: {
          token: localStorage.getItem("token")
        }
      }).then(res => {
        if (res.data.code === 200) {
          ElNotification({
            title: '成功',
            message: res.data.msg,
            type: 'success',
            offset: 100,
          })
        } else {
          ElNotification({
            title: '错误',
            message: res.data.msg,
            type: 'error',
            offset: 100,
          })
        }
        selectMode.value = 1
        currentPage.value = 1
        getScoreAll("/api/getScoreData?pageNum=1&pageSize=10")
      })
      console.log(row)
    }
    const clickAllStu = () => {
      selectMode.value = 1
      currentPage.value = 1
      queryValue.value = ""
      selectValue.value = ""
      getScoreAll("/api/getScoreData?pageNum=1&pageSize=10")

    }
    const resetModifyForm = () => {
      ScoreModifyDialogVisible.value = false
      unref(scoreModifyFormRef).resetFields()
    }
    const submitModifyForm = (formEl) => {
      if (!formEl) return
      formEl.validate((valid) => {
        if (valid) {
          axios.post("/api/updateScore", scoreModifyForm.value, {
            headers: {
              token: localStorage.getItem("token")
            }
          }).then(res =>{
            if (res.data.code === 200) {
              ElNotification({
                title: '成功',
                message: res.data.msg,
                type: 'success',
                offset: 100,
              })
            } else {
              ElNotification({
                title: '错误',
                message: res.data.msg,
                type: 'error',
                offset: 100,
              })
            }
            selectMode.value = 1
            currentPage.value = 1
            getScoreAll("/api/getScoreData?pageNum=1&pageSize=10")
          })
          unref(scoreModifyFormRef).resetFields()
          ScoreModifyDialogVisible.value = false
        }
      })
    }

    return {
      scoreAllData,
      total,
      clickAllStu,
      Search,
      clickToModify,
      handleCurrentChange,
      ScoreDialogVisible,
      selectStu,
      myscoreForm,
      currentPage,
      Edit,
      Plus,
      Delete,
      scoreForm,
      scorerules,
      submitForm,
      resetForm,
      stuSelect,
      scoreFormRef,
      courseAllData,
      clickToDelete,
      scoreModifyForm,
      scoreModifyFormRef,
      scoreModifyrules,
      ScoreModifyDialogVisible,
      resetModifyForm,
      submitModifyForm,
      queryValue,
      selectValue
    }
  }
}
</script>

<style scoped>
#Score {
  margin: 50px auto;
  width: 50%;
  min-width: 1000px;
}
.el-table {
  width: 100%;
}
.el-pagination {
  float: right;
  margin: 50px auto;
}
.el-select .el-input {
  width: 130px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
</style>